package allwe.lock;

import lombok.Data;

import java.util.concurrent.atomic.AtomicStampedReference;

public class CASTest {

    public static int version = 0;
    public static AtomicStampedReference<String> reference = new AtomicStampedReference<>("A", version);

    public static void main(String[] args) throws Exception {
        System.out.println(reference.getReference() + "-" + reference.getStamp());
        System.out.println("============ begin ============");

        TestClass test_1 = new TestClass("test_1", "A", version, "B", version++);
        TestClass test_2 = new TestClass("test_2", "B", version, "A", version++);
        TestClass test_3 = new TestClass("test_3", "B", version, "C", version++); // 这里人为期望修改失败
        TestClass test_4 = new TestClass("test_4", "A", version + 2, "D", version++); // 这里人为期望修改失败

        test_1.start();
        test_2.start();
        test_3.start();
        test_4.start();

        test_1.join();
        test_2.join();
        test_3.join();
        test_4.join();
        System.out.println("============ end ============");

    }

    @Data
    static class TestClass extends Thread {

        private String instanceName;

        private String oldValue;

        private int oldVersion;

        private String newValue;

        private int newVersion;

        public TestClass(String instanceName, String oldValue, int oldVersion, String newValue, int newVersion) {
            this.instanceName = instanceName;
            this.oldValue = oldValue;
            this.oldVersion = oldVersion;
            this.newValue = newValue;
            this.newVersion = newVersion;
        }

        @Override
        public void run() {
            synchronized (CASTest.class) {
                boolean b = reference.compareAndSet(oldValue, newValue, oldVersion, newVersion + 1);
                System.out.println(instanceName + "-" + reference.getReference() + "-" + reference.getStamp());
                System.out.println("==========" + b + "==========\n");
            }
        }
    }
}


